#include"ThreadPool2.h"
#include"WorkThread.h"
#include <unistd.h>
#include <iostream>
ThreadPool::ThreadPool(size_t thsize,size_t tasksize)
:_thidSize(thsize)
,_taskSize(tasksize)
,isRuning(false)
,_que(_taskSize)
{   
    //提前分配好空间
    _threads.reserve(_thidSize);
}
ThreadPool::~ThreadPool(){

}
void ThreadPool::start(){
    //isRuning = true;
    //少了这一步
    for(size_t idx = 0; idx != _thidSize; ++idx){
        unique_ptr<Thread> up(new WorkThread(*this));
        _threads.push_back(std::move(up));
    }
    for(auto &ele : _threads){
        ele->start();
    }
}

void ThreadPool::stop(){
    while(!_que.empty())
    {
        sleep(0.1);
    }
    wake();
    for(auto &ele:_threads){
        ele->stop();
    }
}

Task * ThreadPool::getTask()
{
    return _que.pop();
}

void ThreadPool::addTask(Task*ptask){
    if(ptask){
        _que.push(ptask);
    }
}
void ThreadPool::wake(){
    isRuning = true;
    _que.wakeup();
}
void ThreadPool::doTask(){
    //这里的while很重要，不然子线程没有拿完任务
    //while(!_que.empty())
    //这里很有意思，是因为_que.empty 可能会走到
    //while(!isRuning)
    while(!isRuning){
    //_que.wake();
    Task*ptemp = getTask();

        if(ptemp){
            ptemp->process();
        }
        else{
            cout << "ptask == nullptr" << endl;
        }
    }

}